<?php

namespace App\Http\Controllers\Api\V1;

use Carbon\Carbon;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use App\Supports\Auth\Alipay\AlipayBinder;
use App\Supports\Auth\Alipay\AlipayLogger;
use App\Services\AuthOneDevice\AuthOneDevice;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use App\Http\Controllers\Api\V1\Requests\AuthStoreRequest;
use App\Http\Controllers\Api\V1\Requests\AuthWxminiRequest;
use App\Http\Controllers\Api\V1\Requests\AuthAlipayRequest;
use App\Http\Controllers\Api\V1\Requests\AuthAlipayBindRequest;
use App\Http\Controllers\Api\V1\Requests\AuthWechatBindRequest;
use Rainsens\Dinglog\Facades\Dinglog;
class AuthController extends Controller
{
	public function store()
	{
		$lock = Cache::lock('send_sms_code', 15);

		try {

			if (!$lock->get()) fail('请稍后重试');

			$request = app(AuthStoreRequest::class);

			$captchaData = Cache::get($request->captcha_key);

		

			$credentials['phone'] = $request->phone;
			$credentials['password'] = $request->password;

			if (! $token = auth('api')->setTTL(config('api.auth_ttl'))->attempt($credentials)) {
				fail('用户名或密码错误');
			}

			$user = auth('api')->user();

			if ($user->last_token) {
				try {
					JWTAuth::setToken($user->last_token)->invalidate();
				} catch (TokenExpiredException $e) {}
			}

			$user->update(['last_token' => $token]);

			Cache::forget($request->captcha_key);

		} finally {
			$lock->release();
		}

		return $this->respondWithToken($token)->setStatusCode(201);
	}

	public function alipayPayload()
	{

		$request = app(AuthAlipayBindRequest::class);
		
		$payload = app(AlipayLogger::class)->appPayload();
		Dinglog::text(json_encode($payload->getContent()));
		return response()->json(['payload' => $payload->getContent()]);
	}


	public function alipay()
	{
		$user = app(AlipayLogger::class)->login();
		$token = auth('api')->setTTL(config('api.auth_ttl'))->login($user);
		auth('api')->user()->update(['last_logged_at' => Carbon::now()]);
		return $this->respondWithToken($token)->setStatusCode(201);
	}

	public function alipayBind()
	{
		$lock = Cache::lock('alipay_bind', 30);

		try {

			if (! $lock->get()) fail('处理中...请勿频繁操作');

			
			$user = request()->user();

			app(AlipayBinder::class)->bind($user);

		} finally {
			$lock->release();
		}

		return response(null, 204);
	}

    public function update()
    {
	    if ($user = auth('api')->user()) {
    	    $token = auth('api')->setTTL(config('api.auth_ttl'))->refresh();
	    	app(AuthOneDevice::class)->auth($user, $token);
    	    return $this->respondWithToken($token);
	    }

	    auth('api')->logout();
	    return response(null, 204);
    }

    public function logout()
    {
    	if ($user = auth('api')->user()) {
    		//$user->delFromCache();
	    }

	    auth('api')->logout();
	    return response(null, 204);
    }

    public function destroy()
    {
    	if ($user = auth('api')->user()) {
    		$user->delFromCache();
    		$user->delete();
	    }

    	auth('api')->logout();

    	return response(null, 204);
    }

    protected function respondWithToken(string $token)
    {
    	$expiredAt = auth('api')->factory()->getTTL(); // minutes.
    	return response()->json([
    		'access_token' => $token,
		    'token_type' => 'Bearer',
		    'refresh_at' => ($expiredAt - 14400) * 60, // minus 10 days.
		    'expired_at' => $expiredAt * 60, // seconds.
	    ]);
    }
}
